/**
 * 录单报表
 *
 */

layui.define(['layer', 'form', 'table', 'laydate', 'laytpl', 'zmnBind'], function (exports) {
    let $ = layui.$;
    let form = layui.form, param = {};
    let laytpl = layui.laytpl;
    let layer = layui.layer;
    let table = layui.table;
    let laydate = layui.laydate;
    let zmnBind = layui.zmnBind;

    const cols = [[
        {field: 'receiverName', title: '录入人', align: 'center', width: 200},
        {field: 'totalCount', title: '总单量', align: 'center'},
        {field: 'totalNewCount', title: '新单汇总', align: 'center'},
        {field: 'newCount', title: '新单', align: 'center'},
        {field: 'reworkCount', title: '返修', align: 'center'},
        {field: 'newWithDuplicateCount', title: '新单重复', align: 'center'},
        {field: 'reworkWithDuplicateCount', title: '返修重复', align: 'center'},
        {field: 'doingCount', title: '进行中', align: 'center'},
        {field: 'discardCount', title: '弃单', align: 'center'},
        {field: 'failCount', title: '失败', align: 'center'},
        {field: 'successCount', title: '成功', align: 'center'},
        {field: 'discardRate', title: '弃单率', align: 'center'},
        {field: 'failRate', title: '失败率', align: 'center'},
        {field: 'successRate', title: '成功率', align: 'center'},
        {field: 'totalAmountSumStr', title: '订单收入', align: 'center'},
    ]];
    let tableObj;

    function initPage() {
        // #company
        zmnBind.selectServPlat("platWork", null, true, true);
        zmnBind.selectSubCompany("companyId", null, () => ({plat: platMark.ZMN}), true, true);
        zmnBind.searchChannel('channelId', () => ({rank: 2}), true, false);
        zmnBind.searchOperator('receiverId', () => {
            let deptIdAllStr = document.getElementById('deptIdAll').value;
            let deptIdList = deptIdAllStr.split(',').map(value => Number(value));
            return {"deptIdList": deptIdList};
        }, true, false);
        let date = new Date();
        date.setDate(date.getDate() - 30);
        laydate.render({
            elem: '#startDate',
            value: date
        })
        laydate.render({
            elem: '#endDate',
            value: new Date()
        })
        tableObj = table.render({
            elem: '#zmn-ordered-table',
            url: '/report/ordered/loadData.action',
            where: function () {
                let formData = new FormData(document.querySelector('.search-form'));
                let jsonData = {};
                formData.forEach((value, key) => jsonData[key] = value);
                return jsonData;
            }(),
            done: function (res) {
                $("div[lay-event='LAYTABLE_EXPORT']").attr('lay-event', 'CUSTOM_EXPORT');
                //导出旁边添加帮助按钮
                let hasHelpBtn = $('[lay-event=CUSTOM_HELP]').length !== 0;
                if (!hasHelpBtn) {
                    $(".layui-table-tool-self").prepend(toolbar_help.innerHTML);
                }

                //渲染总计行
                if ($('thead tr').length !== 2) {
                    //获取表格头排序顺序
                    let sort = [];
                    let $title = $('thead tr');
                    $title.find('th').each(function (i) {
                        sort.push(this.dataset['field']);
                    });
                    res.extData.sort = sort;
                    laytpl(totalLine.innerHTML).render(res.extData, function (html) {
                        $('thead').append(html);
                    });
                }
                //修复分页条越界问题
                setTimeout(function () {
                    table.resize(this.id);
                }, 1);
                param = this.where;
                document.tableIns = this;
            },
            height: 'full-150',
            page: true,
            limits: [50, 100, 150, 300],
            limit: 50,
            toolbar: true,
            defaultToolbar: hasExport ? ['exports'] : [],
            response: {
                statusCode: 200,
                msgName: 'message'
            },
            request: {
                pageName: 'pageIndex' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            cols
        });
    }

    function initEvent() {
        //提交事件
        form.on("submit(zmn-form-submit)", function (obj) {
            //清理为空的值
            layui.each(obj.field, function (index, ele) {
                //清理为空的值
                if (ele === '') {
                    delete obj.field[index];
                }
            });
            document.tableIns.where = {};
            tableObj.reload({
                where: obj.field,
                page: {
                    curr: 1
                }
            });
            return false;
        });
        form.on('submit(zmn-form-reset)', function () {
            location.reload();
        });
        //监听头工具事件
        table.on('toolbar(zmn-ordered-table)', function (obj) {
            switch (obj.event) {
                // 表格导出
                case 'CUSTOM_EXPORT':
                    let param = obj.config.where;
                    for (let paramKey in param) {
                        if (param[paramKey] === "") {
                            delete param[paramKey];
                        }
                    }
                    window.location.href = "/report/ordered/export.action?" + $.param(param, true);
                    break;
                case "CUSTOM_HELP":
                    ReportUtil.tips(help_content.innerHTML, this);
                    break;
            }
        });
    }

    initPage();
    initEvent();
    exports('oms_ordered_list');
});
